const Route = require('./route.js')
const Layer = require('./layer.js')
function Router(){
    this.stack = []
}

Router.prototype.route = function(path){
    let route = new Route
    let layer = new Layer(path,route.dispatch.bind(route))
    layer.route = route
    this.stack.push(layer)
    return route
}

Router.prototype.get = function(path,handler){
    let route = this.route(path)
    route.get(handler)
}

Router.prototype.post = function(path,handler){
    let route = this.route(path)
    route.post(handler)
}

Router.prototype.handle = function(req,res,out){
    let path = req.url
    let i = 0
    let match = false
    let next = () =>{
        if(i>=this.stack.length){
            if(!match){
                return out()
            }
            else{
                return
            }
        }

        let layer = this.stack[i++]
        if(layer.match(path)){
            match = true
            layer.handle(req,res,next)
        }

        next()
    }

    next()
}

module.exports = Router
